import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Button, Toast, NavBar, Tag } from "antd-mobile";
import { request } from "../axios/request";
import styles from "./index.module.css";

interface DoctorDetail {
  doctorid: string;
  doctorname: string;
  doctorimage: string;
  doctorstate: string;
  socoadmin: string;
  doctorcity: string;
  doctorprice: number;
  doctorlevel?: string;
  doctorhospital?: string;
  doctordepartment?: string;
  doctorintro?: string;
  doctorspecialty?: string;
  doctorrating?: number;
  doctorconsultations?: number;
  doctorfollowers?: number;
}

function DoctorDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [doctorDetail, setDoctorDetail] = useState<DoctorDetail | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (id) {
      fetchDoctorDetail();
    }
  }, [id]);

  const fetchDoctorDetail = async () => {
    try {
      setLoading(true);
      const response = await request.get("/doctor/detail", {
        params: { id }
      });
      
      if (response.data.code === 20000) {
        setDoctorDetail(response.data.data);
      } else {
        Toast.show({
          icon: 'fail',
          content: '获取医生信息失败',
        });
      }
    } catch (error) {
      console.error("获取医生详情失败:", error);
      Toast.show({
        icon: 'fail',
        content: '网络错误，请稍后重试',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  const handleConsult = () => {
    Toast.show({
      icon: 'success',
      content: '正在为您连接医生...',
    });
  };

  const handleFollow = async () => {
    try {
      const response = await request.post("/doctor/follow", {
        doctorid: id
      });
      
      if (response.data.code === 20000) {
        Toast.show({
          icon: 'success',
          content: '关注成功',
        });
        // 重新获取医生信息以更新关注状态
        fetchDoctorDetail();
      }
    } catch (error) {
      Toast.show({
        icon: 'fail',
        content: '关注失败，请稍后重试',
      });
    }
  };

  if (loading) {
    return (
      <div className={styles.loading}>
        加载中...
      </div>
    );
  }

  if (!doctorDetail) {
    return (
      <div className={styles.error}>
        医生信息不存在
      </div>
    );
  }

  return (
    <div className={styles.container}>
      {/* 顶部导航 */}
      <NavBar onBack={handleBack} style={{ backgroundColor: '#fff' }}>
        医生详情
      </NavBar>

      {/* 医生基本信息 */}
      <div className={styles.header}>
        <div className={styles.doctorInfo}>
          {/* 医生头像 */}
          <div className={styles.avatar}>
            <img 
              src={doctorDetail.doctorimage} 
              alt={doctorDetail.doctorname}
            />
          </div>

          {/* 医生信息 */}
          <div className={styles.info}>
            <div className={styles.name}>
              <h2>{doctorDetail.doctorname}</h2>
              <Tag 
                color={doctorDetail.doctorstate === '在线' ? 'success' : 'default'}
                className={styles.status}
              >
                {doctorDetail.doctorstate}
              </Tag>
            </div>
            
            <div className={styles.detail}>
              {doctorDetail.doctorlevel && `${doctorDetail.doctorlevel} · `}
              {doctorDetail.doctordepartment && `${doctorDetail.doctordepartment} · `}
              {doctorDetail.doctorhospital}
            </div>

            <div className={styles.detail}>
              擅长：{doctorDetail.socoadmin}
            </div>

            <div className={styles.detail}>
              所在城市：{doctorDetail.doctorcity}
            </div>
          </div>
        </div>

        {/* 评分和统计信息 */}
        <div className={styles.stats}>
          <div className={styles.statItem}>
            <div className={`${styles.statValue} ${styles.rating}`}>
              {doctorDetail.doctorrating || 4.8}
            </div>
            <div className={styles.statLabel}>综合评分</div>
          </div>
          <div className={styles.statItem}>
            <div className={`${styles.statValue} ${styles.default}`}>
              {doctorDetail.doctorconsultations || 0}
            </div>
            <div className={styles.statLabel}>咨询次数</div>
          </div>
          <div className={styles.statItem}>
            <div className={`${styles.statValue} ${styles.default}`}>
              {doctorDetail.doctorfollowers || 0}
            </div>
            <div className={styles.statLabel}>关注人数</div>
          </div>
        </div>
      </div>

      {/* 医生介绍 */}
      {doctorDetail.doctorintro && (
        <div className={styles.section}>
          <h3 className={styles.sectionTitle}>医生介绍</h3>
          <div className={styles.sectionContent}>
            {doctorDetail.doctorintro}
          </div>
        </div>
      )}

      {/* 专业特长 */}
      {doctorDetail.doctorspecialty && (
        <div className={styles.section}>
          <h3 className={styles.sectionTitle}>专业特长</h3>
          <div className={styles.sectionContent}>
            {doctorDetail.doctorspecialty}
          </div>
        </div>
      )}

      {/* 底部操作按钮 */}
      <div className={styles.bottomActions}>
        <Button 
          className={styles.followButton}
          onClick={handleFollow}
        >
          关注医生
        </Button>
        <Button 
          color="primary" 
          className={styles.consultButton}
          onClick={handleConsult}
        >
          立即咨询 ￥{doctorDetail.doctorprice}起
        </Button>
      </div>

      {/* 底部占位，防止内容被遮挡 */}
      <div className={styles.bottomSpacer}></div>
    </div>
  );
}

export default DoctorDetail;
